/* 
 * Copyright (C) 2015 fede
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package Control;

import Entity.Calendar;
import Entity.GroupX;
import Entity.RegisteredUser;
import java.security.Principal;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author fede
 */
@Stateless
public class RegisteredUserFacade extends AbstractFacade<RegisteredUser> {

    @PersistenceContext
    EntityManager em;

    /**
     * get entity manager
     *
     * @return entity manager of the class
     */
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    @Inject
    Principal principal;

    @EJB
    private CalendarFacade cf;

    /**
     * This method remove the registered user from DB
     */
    public void unregister() {
        em.remove(getLoggedUser());
    }

    /**
     * this method give the actually logged user
     *
     * @return RegisteredUser logged
     */
    public RegisteredUser getLoggedUser() {
        return em.find(RegisteredUser.class, principal.getName());
    }

    /**
     * This method add a registered user to DB
     *
     * @param user to add
     * @param calendar new Calendar of user
     */
    public void save(RegisteredUser user, Calendar calendar) {

        user.setGroupName(GroupX.REGISTEREDUSER);
        em.persist(user);
        cf.save(calendar);
    }

    /**
     * This method give a string with name and surname of logged user
     *
     * @return string with name and surname
     */
    public String getNameSurname() {

        return em.find(RegisteredUser.class, principal.getName()).getName() + " " + em.find(RegisteredUser.class, principal.getName()).getSurname();
    }

    /**
     * constructor
     */
    public RegisteredUserFacade() {
        super(RegisteredUser.class);
    }

}
